//
//  ZNWBComposeTypeView.swift
//  ZNWeibo
//
//  Created by FunctionMaker on 2017/8/29.
//  Copyright © 2017年 FunctionMaker. All rights reserved.
//

import UIKit
import pop

@objc protocol ZNWBShowComposeController: NSObjectProtocol {
    @objc func presentViewController(clsName: String?)
}

class ZNWBComposeTypeView: UIView {
    
    /// 类型选择容器视图
    @IBOutlet weak var scrollView: UIScrollView!
    /// 返回上一页按钮
    @IBOutlet weak var returnButton: UIButton!
    /// 返回上一页按钮约束
    @IBOutlet weak var returnButtonCenterXCons: NSLayoutConstraint!
    /// 关闭按钮约束
    @IBOutlet weak var closeButtonCenterXCons: NSLayoutConstraint!
    
    weak var delegate: ZNWBShowComposeController?
    
    fileprivate let typeButtonsInfo = [
        ["imageName": "tabbar_compose_idea", "title": "文字", "clsName": "ZNWBTextController"],
                                   ["imageName": "tabbar_compose_photo", "title": "照片/视频"],
                                   ["imageName": "tabbar_compose_weibo", "title": "长微博"],
                                   ["imageName": "tabbar_compose_lbs", "title": "签到"],
                                   ["imageName": "tabbar_compose_review", "title": "点评"],
                                   ["imageName": "tabbar_compose_more", "title": "更多", "actionName": "touchMore"],
                                   ["imageName": "tabbar_compose_friend", "title": "好友圈"],
                                   ["imageName": "tabbar_compose_wbcamera", "title": "微博相机"],
                                   ["imageName": "tabbar_compose_music", "title": "音乐"],
                                   ["imageName": "tabbar_compose_shooting", "title": "拍摄"]
                                   ]
    
    class func composeTypeView() -> ZNWBComposeTypeView{
        let nib = UINib(nibName: "ZNWBComposeTypeView", bundle: nil)
        
        // Xib中将视图的信息从二进制数据中恢复出来后就会调用awakeFromNib
        let view = nib.instantiate(withOwner: nil, options: nil)[0] as! ZNWBComposeTypeView
        
        // 从XIB中加载出来的视图默认为600 * 600
        view.frame = UIScreen.main.bounds
        
        view.setupUI()
        
        return view
    }
    
    func show() {
        guard let rootVC = UIApplication.shared.keyWindow?.rootViewController
        else {
            return
        }
        
        rootVC.view.addSubview(self)
        
        showCurrentView()
        showComposeTypeView()
    }
    
    /// 去掉撰写微博视图
    @IBAction func dismiss(_ sender: UIButton) {
        dismissComposeTypeView()
    }
    
    @IBAction func touchPreviousPage(_ sender: UIButton) {
        scrollView.setContentOffset(CGPoint(), animated: true)
        
        returnButtonCenterXCons.constant = 0
        closeButtonCenterXCons.constant = 0
        
        UIView.animate(withDuration: 0.25, animations: {
            self.layoutIfNeeded()
            
            self.returnButton.alpha = 0
        }) { (_) in
            self.returnButton.isHidden = true
        }
    }
}

extension ZNWBComposeTypeView {
    fileprivate func setupUI() {
        // 强制更新视图布局，使得scrollView的大小有效
        layoutIfNeeded()
        
        let rect = scrollView.bounds
        scrollView.isScrollEnabled = false
        scrollView.showsHorizontalScrollIndicator = false
        
        scrollView.contentSize = CGSize(width: rect.width * 2, height: rect.height)

        for i in 0..<2 {
            let pageView = UIView(frame: rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0))
            addTypeButtons(view: pageView, idx: i * 6)
            
            scrollView.addSubview(pageView)
        }
    }
    
    /// 向视图中添加按钮
    ///
    /// - Parameters:
    ///   - view: 目标视图
    ///   - idx: 从类型数组中取出信息的开始索引
    private func addTypeButtons(view: UIView, idx: Int) {
        let count = 6
        
        if idx >= typeButtonsInfo.count {
            return
        }
        
        for i in idx..<(idx + count) {
            
            if i >= typeButtonsInfo.count {
                break;
            }
            
            // 获取图像与名称
            let dict = typeButtonsInfo[i]
            
            guard let imageName = dict["imageName"],
                  let title = dict["title"]
            else {
                return
            }
            
            let typeButton = ZNWBComposeTypeButton.composeTypeButton(imageNamed: imageName, title: title)
            
            view.addSubview(typeButton)
            
            if let actionName = dict["actionName"] {
                typeButton.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            } else {
                typeButton.addTarget(self, action: #selector(showComposeViewController), for: .touchUpInside)
            }
            
            // 设置类名
            typeButton.clsName = dict["clsName"]
        }
        
        // 按钮布局
        let size = CGSize(width: 100, height: 100)
        let margin = (view.bounds.width - 3 * size.width) / 4
        
        for (idx, button) in view.subviews.enumerated() {
            let col = idx % 3
            
            let x = CGFloat(col + 1) * margin + CGFloat(col) * size.width
            let y = idx > 2 ? view.bounds.height - size.height : 0
            
            button.frame = CGRect(x: x, y: y, width: size.width, height: size.height)
        }
    }
    
    @objc private func touchMore() {
        // 滚动到第二页
        scrollView.setContentOffset(CGPoint(x: scrollView.bounds.width, y: 0), animated: true)
        
        // 动画出现返回按钮
        let constant = scrollView.bounds.width / 6
        
        returnButton.isHidden = false
        returnButton.alpha = 0
        
        returnButtonCenterXCons.constant -= constant
        closeButtonCenterXCons.constant += constant
        
        UIView.animate(withDuration: 0.25, animations: {
            self.layoutIfNeeded()
            
            self.returnButton.alpha = 1
        })
    }
    
    /// 展示撰写控制器
    @objc private func showComposeViewController(typeButton: ZNWBComposeTypeButton) {
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let pageView = scrollView.subviews[page]
        
        for (idx, button) in pageView.subviews.enumerated() {
            let scaler = (button == typeButton) ? 1.5 : 0.5
            let toValue = NSValue.init(cgPoint: CGPoint(x: scaler, y: scaler))
            
            let scalerAnim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
            scalerAnim.toValue = toValue
            scalerAnim.duration = 0.5
            
            button.pop_add(scalerAnim, forKey: "scaleXY")
            
            let alphaAnim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            alphaAnim.toValue = 0.2
            alphaAnim.duration = 0.5
            
            button.pop_add(alphaAnim, forKey: "alpha")
            
            if idx == 0 {
                alphaAnim.completionBlock = { _, _ in
                    self.dismissSelf()
                    
                    let isActive = self.delegate?.responds(to: #selector(ZNWBShowComposeController.presentViewController)) ?? false
                    
                    if isActive {
                        self.delegate?.presentViewController(clsName: typeButton.clsName)
                    }
                }
            }
        }
    }
}

// MARK: - 动画扩展-显示
extension ZNWBComposeTypeView {
    fileprivate func showCurrentView() {
        let anim = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        anim?.fromValue = 0
        anim?.toValue = 1
        anim?.duration = 0.5
        
        pop_add(anim, forKey: "alpha")
    }
    
    fileprivate func showComposeTypeView() {
        for (idx, button) in scrollView.subviews[0].subviews.enumerated() {
            let anim = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            anim?.fromValue = button.center.y + 400
            anim?.toValue = button.center.y
            anim?.springBounciness = 8
            anim?.springSpeed = 8
            
            anim?.beginTime = CACurrentMediaTime() + CFTimeInterval(idx) * 0.025
            
            button.pop_add(anim, forKey: "position.y")
        }
    }
}

// MARK: - 动画扩展-退场
extension ZNWBComposeTypeView {
    fileprivate func dismissComposeTypeView() {
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let pageView = scrollView.subviews[page]
        
        for (idx, button) in pageView.subviews.reversed().enumerated() {
            let anim = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            
            anim?.fromValue = button.center.y
            anim?.toValue = button.center.y + 400
            
            anim?.beginTime = CACurrentMediaTime() + CFTimeInterval(idx) * 0.025
            
            button.pop_add(anim, forKey: "position.y")
            
            // 动画的时长一样，是同时完成的
            anim?.completionBlock = { _, _ in
                    self.dismissSelf()
            }
        }
    }
    
    fileprivate func dismissSelf() {
        let anim = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        anim?.fromValue = 1
        anim?.toValue = 0
        anim?.duration = 0.25
        
        pop_add(anim, forKey: "alpha")
        
        anim?.completionBlock = { _, _ in
            self.removeFromSuperview()
        }
    }
}

